package controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.CaseGoods;
import model.CaseGridInfo;
import model.CaseRoomInfo;
import model.CaseShelfInfo;
import model.Company_info;
import model.GoodsHistory;
import model.T_RelationGridGoods;
import model.User_list;

import com.et.ar.ActiveRecordBase;
import com.et.ar.exception.ActiveRecordException;
import com.et.ar.exception.TransactionException;
import com.et.mvc.JsonView;
import com.wzzz.util.SysDate;

/**
 * 
 * FileName: CasePropertyStorageController.java
 * Author: zhanglibo
 * Date: 2012-6-24
 * Email: zhanglibo@yonyou.com
 * Remark: 
 *
 */
public class CasePropertyStorageController extends ApplicationController {
	private static final String enter = " \n";
	/**
	 * 获得所有未入库的涉案财物
	 * @param rows
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public JsonView getUnStoreGoods(int rows, int page) throws Exception{
		String cond = "1=1 and keep_status=1"; 
		StringBuilder condition = new StringBuilder();
		condition.append(cond);
		List<Object> tmpArgs = new ArrayList<Object>();
		String ajbh = request.getParameter("AJBH");//案件编号
		if(ajbh!=null && ajbh.length()>0)
			buildCondition(condition,"%"+ajbh+"%","CASE_NUM","like");
		String ajlb = request.getParameter("AJLB");//案件类别
		if(ajlb!=null && ajlb.length()>0)
			buildCondition(condition,"%"+ajlb+"%","CASE_TYPE","like");
		String ajmc = request.getParameter("AJMC");//案件名称
		if(ajmc!=null && ajmc.length()>0)
			buildCondition(condition,"%"+ajmc+"%","CASE_NAME","like");
		String wpsbdw = request.getParameter("WPSBDW");//物品上报单位
		if(wpsbdw!=null && wpsbdw.length()>0)
			buildCondition(condition,"%"+wpsbdw+"%","GOODS_COMPANY","like");
		String wpsbr = request.getParameter("WPSBR");  //物品上报人
		if(wpsbr!=null && wpsbr.length()>0)
			buildCondition(condition,"%"+wpsbr+"%","CASE_TO_MAN","like");
		String sbsj = request.getParameter("SBSJ");   //上报时间
		if(sbsj!=null && sbsj.length()>0)
			buildCondition(condition,"%"+sbsj+"%","ENTER_DATE","like");
		Object[] args = tmpArgs.toArray();
		long total = CaseGoods.count(CaseGoods.class,condition.toString(),args);
		List<CaseGoods> list = CaseGoods.findAll(CaseGoods.class, condition.toString(),args,"goods_id",rows, (page - 1) * rows);
		// 构造JSON用的数据结构并返回JSON视图
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", total);//数据总数
		result.put("rows", list);//具体数据
		return new JsonView(result);
	}
	/**
	 * 构造查询条件得方法
	 * @param cond 查询条件，第一次是 1=1 ，然后不停得拼接 and条件
	 * @param value 查询得值，如果是like查询，需要手动加'%' %value%
	 * @param target 目标字段
	 * @param operate 操作符
	 */
	private void buildCondition(StringBuilder cond,String value,String target,String operate){
		if (value != null && !"".equals(value) && value.replaceAll("%","").length() > 0) {
			cond.append(" and ").append(target).append(" ").append(operate)
					.append(" '").append(value).append("'");
		}
	}
	/**
	 * 登记入库页面，下拉选保管室，根据操作人员所在单位查询
	 * @return
	 * @throws ActiveRecordException
	 */
	public JsonView getCaseRoom() throws ActiveRecordException{
		User_list ul = (User_list)session.getAttribute("sessionAccount");
		String company_id = ul.getUser_company();
		String cond = "room_company='"+company_id+"'";
		List<Object> tmpArgs = new ArrayList<Object>();
		Object[] args = tmpArgs.toArray();
		List<CaseRoomInfo> caseRoomInfo = CaseRoomInfo.findAll(CaseRoomInfo.class,cond, args); 
		return new JsonView(caseRoomInfo);
	}
	/**
	 * 登记入库页面，下拉选保管柜，根据保管室ID查询
	 * @param room_id
	 * @return
	 * @throws ActiveRecordException
	 */
	public JsonView getShelfByCaseRoom(String room_id) throws ActiveRecordException{
		String condition = "1=1 and shelf_status=1 and case_room_id="+room_id;
		List<Object> tmpArgs = new ArrayList<Object>();
		Object[] args = tmpArgs.toArray();
		List<CaseShelfInfo> list = CaseShelfInfo.findAll(CaseShelfInfo.class,condition,args);
		return new JsonView(list);
	}
	public JsonView getCompanyInfo() throws ActiveRecordException{
		String condition = "1=1";
		List<Object> tmpArgs = new ArrayList<Object>();
		Object[] args = tmpArgs.toArray();
		List<Company_info> list = Company_info.findAll(Company_info.class,condition,args,"company_id");
		return new JsonView(list);
	}
	/**
	 * 登记入库页面，选择保管柜后，动态生成规则格式，返回行、列、格子信息、物品格子关联表得数据
	 * @param shelf_id
	 * @return
	 * @throws ActiveRecordException
	 * @throws ClassNotFoundException 
	 */
	public JsonView getCabinet(String shelf_id) throws ActiveRecordException, ClassNotFoundException{
		String condition = "1=1 and shelf_id="+shelf_id;
		Map<String, Object> result = new HashMap<String, Object>();
		CaseShelfInfo shelf = CaseShelfInfo.find(CaseShelfInfo.class, shelf_id);
		List<CaseGridInfo> gridInfoList = CaseGridInfo.findAll(CaseGridInfo.class, condition);
		if(gridInfoList.size()!=(Integer.parseInt(shelf.getShelf_con())*Integer.parseInt(shelf.getShelf_row()))){
			result.put("error", "数据中格子的数量与架子设定的数量不符！！");
		}
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT TCGI.GOODS_ID,").append(enter);
		sql.append("       TCGI.GOODS_NAME,").append(enter);
		sql.append("       TCGI.GOODS_NUM,").append(enter);
		sql.append("       TCGI.CASE_NAME,").append(enter);
		sql.append("       TCGI.GOODS_TCODE,").append(enter);
		sql.append("       TRGG.CASE_ROOM_ID,").append(enter);
		sql.append("       TRGG.CASE_SHELF_ID,").append(enter);
		sql.append("       TRGG.CASE_GRID_ID,").append(enter);
		sql.append("       TRGG.CREATE_DATE").append(enter);
		sql.append("  FROM T_RELATION_GRID_GOODS TRGG").append(enter);
		sql.append(" INNER JOIN T_CASE_GOODS_INFO TCGI ON TRGG.T_CODE = TCGI.GOODS_TCODE").append(enter);
		sql.append("WHERE TRGG.CASE_SHELF_ID=").append(shelf_id).append(enter);
		List<Map<String,Object>> shelfGoodslist = T_RelationGridGoods.getResultMap(T_RelationGridGoods.class,sql.toString(),null, "",0,Integer.MAX_VALUE);
		//List<GLXXB> GLXXB.findAll(GLXXB.class,"1=1 and BGG_GZHM="+shelf_id);
		result.put("col_Num", shelf.getShelf_con());
		result.put("row_Num", shelf.getShelf_row());
		result.put("gridInfoList", gridInfoList);
		result.put("shelfGoodslist", shelfGoodslist);
		return new JsonView(result);
	}
	/**
	 * 登记入库的方法
	 * @return JsonView
	 * TODO 现在只在涉案物品关联信息表添加了记录，并修改了物品表中的信息，但是没有在历史记录表中添加记录
	 */
	public JsonView doStorage(){
		User_list ul = (User_list)session.getAttribute("sessionAccount");
		String selectedGoodsIds = request.getParameter("selectedGoodsIds").substring(0,request.getParameter("selectedGoodsIds").length()-1);
		String t_code = request.getParameter("t_code");
		String gridID = request.getParameter("gridID");
		String room_id = request.getParameter("room_id");
		String shelf_id = request.getParameter("shelf_id");
		StringBuilder updates = new StringBuilder();
		updates.append("goods_tcode='").append(t_code).append("' ");
		updates.append(", keep_status=2 ");
		StringBuilder conditions = new StringBuilder();
		conditions.append(" goods_id in (").append(selectedGoodsIds).append(")");
		try {
			ActiveRecordBase.beginTransaction();
			CaseGoods.updateAll(CaseGoods.class, updates.toString(), null, conditions.toString(), null);
			T_RelationGridGoods gridgoods = new T_RelationGridGoods();
			gridgoods.setCASE_GRID_ID(gridID);
			gridgoods.setT_CODE(t_code);
			gridgoods.setCASE_ROOM_ID(room_id);
			gridgoods.setCASE_SHELF_ID(shelf_id);
			gridgoods.setCREATE_DATE(SysDate.getToday());
			gridgoods.setSTATUS("已入库");
			gridgoods.setOPERATE_COMPANY(ul.getUser_company());
			gridgoods.setCREATE_BY(String.valueOf(ul.getUser_id()));
			gridgoods.save();
			CaseGridInfo.updateAll(CaseGridInfo.class, "grid_status=1", null, "grid_id="+gridID, null);
			//轨迹表数据，因为物品可能是多个，所以这里要有循环
			String [] sIds = selectedGoodsIds.split(",");
			for(String selectGoodsId:sIds){
				GoodsHistory history = new GoodsHistory();
				history.setCASE_GOODS_ID(selectGoodsId);  //物品ID
				history.setCASE_GOODS_TCODE(t_code);      //物品条形码
				history.setCASE_ROOM_ID(room_id);         //保管室
				history.setSHELF_ID(shelf_id);            //保管柜
				history.setGRID_ID(gridID);               //保管柜格子ID
				history.setGOODS_STATUS("已入库");         //物品状态
				history.setHISTORY_COMPANY(ul.getUser_company());   //轨迹表操作单位
				history.setHISTORY_PERSON(String.valueOf(ul.getUser_id()));  //轨迹表操作人
				history.setHISTORY_DATE(SysDate.getToday());    //轨迹表操作时间
				history.setSTATUS("0");                   //财物处理操作标识  0入库
				history.save();
			}
			
//			history.setCASE_GOODS_ID()
			ActiveRecordBase.commit();
			JsonView view = new JsonView("success:true");
			view.setContentType("text/html;charset=utf-8");
			return view;
		} catch (ActiveRecordException e) {
			try {
				e.printStackTrace();
				JsonView view = new JsonView("success:false");
				view.setContentType("text/html;charset=utf-8");
				
				ActiveRecordBase.rollback();
				return view;
			} catch (TransactionException e1) {
				e1.printStackTrace();
				JsonView view = new JsonView("success:false");
				view.setContentType("text/html;charset=utf-8");
				return view;
			}
		}
		
		
	}
}
